package accs.model.io;

import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import accs.model.UserPasswordPair;

/**
 * Removes duplicates from a UserPasswordPair-Stream or from a list of them.
 * @author syxolk
 */
public class DuplicateFilter extends UserPasswordReader {
	private UserPasswordReader reader;
	private List<UserPasswordPair> list=new ArrayList<UserPasswordPair>();
	
	public DuplicateFilter(UserPasswordReader reader) {
		this.reader=reader;
	}
	
	/**
	 * Reads the next pair. All pairs are stored and duplicates are not returned.
	 */
	public UserPasswordPair read() throws IOException {
		UserPasswordPair pair=null;
		while((pair=reader.read())!=null && list.contains(pair)) {}
		if(pair!=null) list.add(pair);
		return pair;
	}

	/**
	 * Close the underlying reader.
	 */
	public void close() throws IOException {
		reader.close();
	}
	
	/**
	 * Filters a list of UserPasswordPairs by using a java.util.Set.
	 * @param list list of pairs
	 * @return filtered list
	 */
	public static List<UserPasswordPair> filter(List<UserPasswordPair> list) {
		Set<UserPasswordPair> set=new LinkedHashSet<UserPasswordPair>(list);
		return new ArrayList<UserPasswordPair>(set);
	}
}